package com.chang.soul.util;

import com.chang.soul.exception.ResultCode;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;

/**
 * @author xiaoqingyang@vip.henu.edu.cn
 * @date 2021/3/24 21:45
 */

public class ResultUtil<T> implements Serializable {
    public ResultUtil() {
    }

    public static <T> Result<T> success(T object) {
        Result<T> result = new Result<>();
        result.setStatus(ResultCode.SUCCESS.code());
        result.setMsg("success");
        result.setResults(object);
        return result;
    }

    public static Result<Object> success() {
        return success((Object)null);
    }

    public static Result<Object> error(Integer code, String msg) {
        Result<Object> result = new Result<>();
        result.setStatus(code);
        result.setMsg(msg);
        result.setResults((Object)null);
        return result;
    }

    public static Result<Object> error(ResultCode resultCode) {
        Result<Object> result = new Result<Object>();
        result.setStatus(resultCode.code());
        result.setMsg(resultCode.message());
        result.setResults((Object)null);
        return result;
    }

    public static Result<Object> error(String errorMsg) {
        Result<Object> result = new Result<Object>();
        result.setStatus(ResultCode.FAIL.code());
        result.setMsg(errorMsg);
        result.setResults((Object)null);
        return result;
    }

    public static Result<Object> error(BindingResult result) {
        StringBuilder errorSb = new StringBuilder();
        List<ObjectError> list = result.getAllErrors();

        for (ObjectError error : list) {
            errorSb.append(error.getDefaultMessage());
        }

        return error(ResultCode.FAIL.code(), errorSb.toString());
    }


    public static Result<Object> error(ResultCode resultCode, Object obj) {
        Result<Object> result = new Result<Object>();
        result.setStatus(resultCode.getCode());
        result.setMsg(resultCode.getMessage());
        result.setResults(obj);
        return result;
    }

    public static void responseJson(HttpServletResponse response, Object result) {
        try {
            Gson gson = new Gson();
            response.getWriter().print(gson.toJson(result));
            response.flushBuffer();
        } catch (IOException var3) {
            var3.printStackTrace();
        }

    }
}
